package com.lzh.lzhframework.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzh.lzhframework.dao.FeedbackMapper;
import com.lzh.lzhframework.domain.ResponseResult;
import com.lzh.lzhframework.domain.dto.feedback.AddFeedbackDto;
import com.lzh.lzhframework.domain.dto.feedback.QueryFeedbackDto;
import com.lzh.lzhframework.domain.dto.feedback.QueryMyFeedbackDto;
import com.lzh.lzhframework.domain.dto.feedback.ReplyFeedbackDto;
import com.lzh.lzhframework.domain.entity.FeedbackEntity;
import com.lzh.lzhframework.domain.entity.mongo.AdminReplyEntity;
import com.lzh.lzhframework.domain.vo.PageVo;
import com.lzh.lzhframework.domain.vo.feedback.FeedbackStatusVo;
import com.lzh.lzhframework.domain.vo.feedback.FeedbackTypeVo;
import com.lzh.lzhframework.domain.vo.feedback.QueryFeedbackPageVo;
import com.lzh.lzhframework.enums.FeedbackStatusEnum;
import com.lzh.lzhframework.enums.FeedbackTypeEnum;
import com.lzh.lzhframework.exception.SystemException;
import com.lzh.lzhframework.service.FeedbackService;
import com.lzh.lzhframework.utils.BeanCopyUtils;
import com.lzh.lzhframework.utils.SecurityUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * (Feedback)表服务实现类
 *
 * @author luzhiheng
 * @since 2023-11-27 11:47:41
 */
@Service("feedbackService")
public class FeedbackServiceImpl extends ServiceImpl<FeedbackMapper, FeedbackEntity> implements FeedbackService {

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Resource
    private MongoTemplate mongoTemplate;

    @Override
    public void addFeedback(AddFeedbackDto dto) {
        Long userId = SecurityUtils.getUserId();
        FeedbackEntity feedbackEntity = new FeedbackEntity(dto);
        this.save(feedbackEntity);
        Long feedbackId = feedbackEntity.getId();
        // 用户发送反馈消息，发送到消息队列
        rabbitTemplate.convertAndSend("user.feedback", "user.feedback", feedbackId + "#" + userId);
    }

    @Override
    public ResponseResult queryFeedbackPage(QueryFeedbackDto dto) {
        Page<FeedbackEntity> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        LambdaQueryWrapper<FeedbackEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(dto.getTitle()), FeedbackEntity::getTitle, dto.getTitle());
        queryWrapper.like(StringUtils.isNotEmpty(dto.getCreateName()), FeedbackEntity::getCreateName, dto.getCreateName());
        queryWrapper.like(StringUtils.isNotEmpty(dto.getContent()), FeedbackEntity::getFeedbackContent, dto.getContent());
        queryWrapper.eq(dto.getStatus() != null && dto.getStatus() != -1, FeedbackEntity::getStatus, dto.getStatus());
        queryWrapper.eq(dto.getType() != null && dto.getType() != -1, FeedbackEntity::getType, dto.getType());
        queryWrapper.orderByDesc(FeedbackEntity::getCreateTime);
        this.page(page, queryWrapper);

        List<QueryFeedbackPageVo> pageVoList = page.getRecords().stream().map(e -> {
            QueryFeedbackPageVo vo = BeanCopyUtils.copyBean(e, QueryFeedbackPageVo.class);
            vo.setStatus(FeedbackStatusEnum.codeToValue(e.getStatus()));
            return vo;
        }).collect(Collectors.toList());
        PageVo pageVo = new PageVo(page.getTotal(), pageVoList);
        return ResponseResult.success(pageVo);
    }

    @Override
    public List<FeedbackStatusVo> queryFeedbackStatus() {
        return Stream.of(FeedbackStatusEnum.values())
                .map(feedbackStatusEnum -> new FeedbackStatusVo(feedbackStatusEnum.code, feedbackStatusEnum.value))
                .collect(Collectors.toList());
    }

    @Override
    public void replyFeedback(ReplyFeedbackDto dto) {
        FeedbackEntity feedbackEntity = this.getById(dto.getId());
        if (feedbackEntity == null) {
            throw new SystemException("反馈不存在");
        }
        if (!feedbackEntity.getStatus().equals(FeedbackStatusEnum.BEGIN.code)) {
            throw new SystemException("反馈已拒绝或已完成，无法回复");
        }
        feedbackEntity.setReplyContent(dto.getReplyContent());
        feedbackEntity.setStatus(FeedbackStatusEnum.FINISH.code);
        this.updateById(feedbackEntity);

        // 异步保存用户未读反馈信息状态记录
        AdminReplyEntity adminReplyEntity = new AdminReplyEntity(feedbackEntity);
        mongoTemplate.insert(adminReplyEntity);
    }

    @Override
    public List<FeedbackTypeVo> queryFeedbackType() {
        return Stream.of(FeedbackTypeEnum.values())
                .map(feedbackTypeEnum -> new FeedbackTypeVo(feedbackTypeEnum.code, feedbackTypeEnum.value))
                .collect(Collectors.toList());
    }

    @Override
    public void rejectFeedback(Long id) {
        FeedbackEntity feedbackEntity = this.getById(id);
        if (feedbackEntity == null) {
            throw new SystemException("反馈不存在");
        }
        feedbackEntity.setStatus(FeedbackStatusEnum.REJECT.code);
        this.updateById(feedbackEntity);
    }

    @Override
    public ResponseResult queryMyFeedbackPage(QueryMyFeedbackDto dto) {
        Page<FeedbackEntity> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        IPage<FeedbackEntity> iPage = baseMapper.queryByUserName(page, dto);
        PageVo pageVo = new PageVo(iPage.getTotal(), iPage.getRecords());
        return ResponseResult.success(pageVo);
    }
}

